This creates a canvas where you can draw a handwritten digit.


In [1]:
input_form = """
<table>
<td style="border-style: none;">
<div style="border: solid 2px #666; width: 143px; height: 144px;">
<canvas width="140" height="140"></canvas>
</div></td>
<td style="border-style: none;">
<button onclick="clear_value()">Clear</button>
</td>
</table>
"""

javascript = '''
<script type="text/Javascript">
    var pixels = [];
    for (var i = 0; i < 28*28; i++) pixels[i] = 0;
    var click = 0;

    var canvas = document.querySelector("canvas");
    canvas.addEventListener("mousemove", function(e){
        if (e.buttons == 1) {
            click = 1;
            canvas.getContext("2d").fillStyle = "rgb(0,0,0)";
            canvas.getContext("2d").fillRect(e.offsetX, e.offsetY, 8, 8);
            x = Math.floor(e.offsetY * 0.2);
            y = Math.floor(e.offsetX * 0.2) + 1;
            for (var dy = 0; dy < 2; dy++){
                for (var dx = 0; dx < 2; dx++){
                    if ((x + dx < 28) && (y + dy < 28)){
                        pixels[(y+dy)+(x+dx)*28] = 1;
                    }
                }
            }
        } else {
            if (click == 1) set_value();
            click = 0;
        }
    });
    
    function set_value(){
        var result = ""
        for (var i = 0; i < 28*28; i++) result += pixels[i] + ","
        var kernel = IPython.notebook.kernel;
        kernel.execute("image = [" + result + "]");
        kernel.execute("f = open('request.json', 'w')");
        kernel.execute("f.write('{\\"inputs\\":%s}' % image)");
        kernel.execute("f.close()");
    }
    
    function clear_value(){
        canvas.getContext("2d").fillStyle = "rgb(255,255,255)";
        canvas.getContext("2d").fillRect(0, 0, 140, 140);
        for (var i = 0; i < 28*28; i++) pixels[i] = 0;
    }
</script>
'''

from IPython.display import HTML
HTML(input_form + javascript)


Out[1]:

Now you can send a request to make a prediction.


In [2]:
%%bash
MODEL_NAME="MNIST"
gcloud ai-platform predict --model ${MODEL_NAME} --json-instances request.json | tee predict.txt


CLASSES  PROBABILITIES
3        [3.178637535018992e-29, 5.019398958601389e-18, 2.553775243286402e-22, 1.0, 1.6729859155339614e-23, 1.6934683392340924e-16, 3.5852181235363655e-26, 1.1448885891453676e-15, 3.574062965565033e-18, 1.5919192670572453e-20]

You can also draw a bar chart with the prediction result.


In [3]:
import matplotlib.pyplot as plt
import re

with open('predict.txt') as prediction:
  head = prediction.readline()
  result = prediction.readline()
r = re.compile("\[(.+)\]")
pred = r.search(result).group(1).split(',')
pred = map(lambda x: float(x), pred)

fig = plt.figure(figsize=(4,2))
subplot = fig.add_subplot(1,1,1)
subplot.set_xticks(range(10))
subplot.set_xlim(-0.5,9.5)
subplot.set_ylim(0,1)
subplot.bar(range(10), pred, align='center')


Out[3]:
<Container object of 10 artists>